package com.diy.springframework.step;

import cn.hutool.core.util.StrUtil;
import com.diy.springframework.step.definition.BeanDefinition;

import java.lang.reflect.Method;

/**
 * @program: diy_spring
 * @description:
 * @author: CaoYong
 * @create: 2021-07-24 11:05
 **/
public class DisposableBeanAdapter implements DisposableBean{

    private final Object bean;
    private final String beanName;
    private String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }

    @Override
    public void destory() throws Exception {

        if (bean instanceof DisposableBean) {
            ((DisposableBean) bean).destory();
        }

        if (StrUtil.isNotEmpty(destroyMethodName) && !(bean instanceof  DisposableBean && "destory".equals(this.destroyMethodName))) {
            Method destroyMethod = bean.getClass().getMethod(destroyMethodName);
            if (null == destroyMethod) {
                throw new Exception("Couldn't find a destroy method:" + destroyMethodName);
            }
            destroyMethod.invoke(bean);
        }

    }
}
